package com.chris.core.socket.netty.handler;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 对象处理器-- 客户端
 * 苏斌 2022-3-29
 */
public class ByteClientHandler extends ChannelInboundHandlerAdapter {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    /**
     * 当通道就绪
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

    }

    /**
     * 读取服务端发送数据
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // super.channelRead(ctx,msg);
        //注意区别 ：byteBuffer(nio) ByteBuf (netty)
       //  ByteBuf byteBuf =(ByteBuf)msg;
        //  log.debug("获取客户端发送数据：" +byteBuf.toString(CharsetUtil.UTF_8));
        // String tip= byteBuf.toString(CharsetUtil.UTF_8);
        log.debug("获取服务端发送数据：" + new String((byte[])msg,CharsetUtil.UTF_8 ));
//传递给下一个pinline
        super.channelRead(ctx,msg);

    }



    /**
     * 异常处理
     * 一般是关闭通道
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        log.debug("客户端通道捕获异常 客户端地址:"+ctx.channel().remoteAddress() +" 问题:"+cause.toString() ) ;
    }

    /**
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        log.debug("客户端下线 地址："+channel.remoteAddress());
    }

}
